package com.fast.mybatis.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class ObjectUtil {
	private static final Logger log = LoggerFactory.getLogger(ObjectUtil.class);

	public static Object invokeMethod(Class<?> clazz, String methodName, Class<?>[] paraClazzs, Object obj,
			Object... paras) {
		try {	
			Method method = ObjectUtil.getMethod(clazz, methodName, paraClazzs);
			if (method == null) {
				log.error(methodName + " is null.");
				return null;
			}
		
				return invokeMethod(method, obj, paras);
			} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
				log.error(e.getMessage());
				return null;
			}
		
	}
	
	public static Object invokeMethod(Method method, Object obj, Object... paras)
			throws IllegalAccessException,InvocationTargetException{
		try {
			return method.invoke(obj, paras);
		} catch (InvocationTargetException | IllegalAccessException e) {
			log.error(e.getMessage(), e);
			throw e;
		} 
	}
	
	public static Method getMethod(Class<?> clazz, String methodName, Class<?>... paraClazzs)
			throws NoSuchMethodException {
		return getMethod(clazz, methodName, true, paraClazzs);
	}
	
	public static Method getMethod(Class<?> clazz, String methodName, Boolean throwError, Class<?>... paraClazzs) throws NoSuchMethodException
			 {
		try {
			return clazz.getMethod(methodName, paraClazzs);
		} catch (NoSuchMethodException e) {
			log.error(e.getMessage());
			throw e;
		}
	}

}
